<template>
  <!-- 主查询表单（商场主题） -->
  <el-card class="mall-query-card">
    <el-form
        :inline="true"
        :model="queryForm"
        class="main-query-form mall-query-form"
        label-width="80px"
    >
      <el-form-item label="商品名称">
        <el-input
            v-model="queryForm.gname"
            placeholder="请输入商品名称"
            clearable
            class="mall-input"
        />
      </el-form-item>

      <el-form-item label="审核状态">
        <el-select
            v-model="queryForm.processStatus"
            placeholder="全部"
            clearable
            class="mall-select"
            style="width: 150px"
        >
          <el-option label="全部" value="" />
          <el-option label="未审核" value="2" />
          <el-option label="审核通过" value="1" />
          <el-option label="审核未通过" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item label="生效时间">
        <el-date-picker
            v-model="queryForm.beginTime"
            type="date"
            placeholder="开始日期"
            class="mall-date"
            value-format="YYYY-MM-DD"
            @change="handleBeginTimeChange"
            style="width: 100px"
        />
      </el-form-item>

      <el-form-item label="失效时间">
        <el-date-picker
            v-model="queryForm.endTime"
            type="date"
            placeholder="结束日期"
            class="mall-date"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledEndDate"
            style="width: 100px"
        />
      </el-form-item>

      <el-form-item class="query-buttons">
        <el-button type="primary" @click="queryWithCondition" class="mall-btn mall-primary">查询</el-button>
        <el-button @click="clearQueryForm" class="mall-btn mall-default">重置</el-button>
        <el-button type="success" @click="addAdjustDialog = true" class="mall-btn mall-success">新增价格调整</el-button>
        <el-button type="danger" @click="delBatch" class="mall-btn mall-danger">删除选中</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 详情 -->
  <ViewDialog ref="viewDialogRef" />

  <!-- 审核跟踪对话框 -->
  <AuditTraceDialog ref="auditTraceDialogRef" />

  <!-- 新增价格调整对话框 -->
  <el-dialog
      title="商品调价"
      v-model="addAdjustDialog"
      width="700px"
      :before-close="handleClose"
      class="mall-dialog"
  >
    <div class="dialog-header">
      <h3>🛒 商品调价信息</h3>
    </div>
    <el-form :model="form" label-width="120px" class="dialog-form mall-dialog-form" ref="formRef">
      <!-- 商品信息部分 -->
      <el-form-item label="商品ID:" prop="goodsId" :rules="formRules.goodsId">
        <div class="form-item-content">
          <el-input v-model="form.goodsId" class="mall-input mall-disabled" disabled />
          <el-button type="primary" @click="openchooseGoodsDialog" class="mall-btn mall-primary">选择商品</el-button>
        </div>
      </el-form-item>

      <el-form-item label="商品名称:">
        <el-input v-model="form.goodsName" class="mall-input mall-disabled" disabled />
      </el-form-item>

      <el-form-item label="商品库存:">
        <el-input v-model="form.goodsStock" class="mall-input mall-disabled" disabled />
      </el-form-item>

      <el-form-item label="商品原始价格:">
        <div class="price-group">
          <div class="price-item">
            <span class="price-label">市场价</span>
            <el-input
                v-model="form.originalMarketPrice"
                placeholder="市场价"
                class="mall-input mall-disabled price-input"
                disabled
            />
          </div>
          <div class="price-item">
            <span class="price-label">商城价</span>
            <el-input
                v-model="form.originalMallPrice"
                placeholder="商城价"
                class="mall-input mall-disabled price-input"
                disabled
            />
          </div>
        </div>
      </el-form-item>

      <!-- 调价幅度 -->
      <el-form-item label="商品调价幅度:" prop="percent" :rules="formRules.percent">
        <div class="adjust-group">
          <el-radio-group
              v-model="form.adjustWay"
              class="mall-radio-group"
              @change="handleAdjustWayChange"
          >
            <el-radio label="absolute" class="mall-radio">绝对值</el-radio>
            <el-radio label="percentage" class="mall-radio">百分比</el-radio>
          </el-radio-group>
          <el-input
              v-model="form.percent"
              class="mall-input adjust-input"
              :placeholder="form.adjustWay === 'absolute' ? '输入调整值' : '输入百分比(如132%)'"
              @input="handlePercentInput"
              :maxlength="form.adjustWay === 'percentage' ? 5 : null"
          />
        </div>
      </el-form-item>

      <!-- 调整后价格 -->
      <el-form-item label="调整后的价格:" prop="adjustMarketPrice" :rules="formRules.adjustMarketPrice">
        <div class="price-group">
          <div class="price-item">
            <span class="price-label">市场价</span>
            <el-input
                v-model="form.adjustMarketPrice"
                placeholder="市场价"
                class="mall-input mall-disabled price-input"
                disabled
            />
          </div>
          <div class="price-item">
            <span class="price-label">商城价</span>
            <el-input
                v-model="form.adjustShoppingPrice"
                placeholder="商城价"
                class="mall-input mall-disabled price-input"
                disabled
                prop="adjustShoppingPrice"
                :rules="formRules.adjustShoppingPrice"
            />
          </div>
        </div>
      </el-form-item>

      <!-- 生效时间 -->
      <el-form-item label="希望生效时间:" prop="beginTime" :rules="formRules.beginTime">
        <el-date-picker
            v-model="form.beginTime"
            type="date"
            placeholder="选择生效日期"
            class="mall-date full-date"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledEffectiveDate"
            @change="handleEffectiveTimeChange"
        />
      </el-form-item>

      <!-- 失效时间 -->
      <el-form-item label="希望失效时间:" prop="endTime" :rules="formRules.endTime">
        <el-date-picker
            v-model="form.endTime"
            type="date"
            placeholder="请先选择生效时间"
            class="mall-date full-date"
            value-format="YYYY-MM-DD"
            :disabled="!form.beginTime"
            :disabled-date="disabledInvalidDate"
            @click="checkEffectiveTimeFirst"
        />
      </el-form-item>

      <!-- 调价原因 -->
      <el-form-item label="调价原因:" prop="reason" :rules="formRules.reason">
        <el-input type="textarea" v-model="form.reason" rows="3" class="mall-textarea" placeholder="请输入调价原因..." />
      </el-form-item>

      <el-form-item label="备注:">
        <el-input type="textarea" v-model="form.remark" rows="3" class="mall-textarea" placeholder="请输入备注信息..." />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer mall-footer">
        <el-button @click="addAdjustDialog = false" class="mall-btn mall-default">取消</el-button>
        <el-button type="primary" @click="saveForm" class="mall-btn mall-primary">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 商品价格调整表格 -->
  <el-card class="mall-table-card">
    <template #header>
      <div class="table-header">
        <span class="table-title">📊 价格调整列表</span>
        <span class="table-tips">共 {{ pageInfo.total }} 条记录</span>
      </div>
    </template>
    <el-table :data="priceTableData" class="mall-table" @selection-change="getRowIds">
      <el-table-column prop="id" label="序号" min-width="50" align="center" />
      <el-table-column type="selection" min-width="55" align="center" />
      <el-table-column prop="gname" label="商品名称" min-width="180" show-overflow-tooltip />
      <el-table-column prop="oldShopPrice" label="原商城价" min-width="100" align="center">
        <template #default="scope">
          <span class="price-cell">¥{{ scope.row.oldShopPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="adjustShoppingPrice" label="调整后商城价" min-width="120" align="center">
        <template #default="scope">
          <span class="price-cell highlight">¥{{ scope.row.adjustShoppingPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="beginTime" label="生效时间" min-width="160" align="center">
        <template #default="scope">
          <span class="date-cell">{{ formatDateTime(scope.row.beginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="processStatus" label="审批状态" min-width="100" align="center">
        <template #default="scope">
          <span
              :class="{
                'status-unreviewed': scope.row.processStatus === '2',
                'status-passed': scope.row.processStatus === '1',
                'status-rejected': scope.row.processStatus === '0'
              }"
              class="status-badge"
          >
            {{
              scope.row.processStatus === '0' ? '审核未通过' :
                  scope.row.processStatus === '1' ? '审核通过' : '未审核'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="300" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <el-button type="primary" size="small" @click="handleView(scope.row)" class="mall-btn mall-primary">查看</el-button>
            <template v-if="scope.row.processStatus === '2'">
              <el-button type="success" size="small" @click="handleEdit(scope.row)" class="mall-btn mall-success">修改</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)" class="mall-btn mall-danger">删除</el-button>
            </template>
            <el-button type="info" size="small" @click="handleAuditTrace(scope.row)" class="mall-btn mall-info">审核跟踪</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pageInfo.pageNum"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[3, 5, 7]"
          :total="pageInfo.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="pageSizeChange"
          @current-change="pageNumChange"
          class="mall-pagination"
      />
    </div>
  </el-card>

  <!-- 选择商品列表对话框 -->
  <el-dialog
      v-model="chooseGoodsDialog"
      title="选择商品"
      width="1200px"
      :close-on-click-modal="false"
      @close="closeQueryPro"
      class="mall-dialog"
  >
    <div class="dialog-header">
      <h3>🛍️ 商品选择</h3>
    </div>

    <el-card class="mall-search-card">
      <el-form
          :inline="true"
          :model="queryProductForm"
          class="horizontal-form mall-search-form"
          label-width="70px"
      >
        <el-form-item label="商品名称">
          <el-input
              v-model="queryProductForm.pname"
              clearable
              placeholder="请输入名称"
              class="mall-input"
              style="width: 120px"
          />
        </el-form-item>

        <el-form-item label="商品型号">
          <el-input
              v-model="queryProductForm.pmodel"
              clearable
              placeholder="请输入型号"
              class="mall-input"
              style="width: 120px"
          />
        </el-form-item>

        <el-form-item label="查询条件">
          <el-select
              v-model="queryProductForm.queryconditon"
              placeholder="选择条件"
              clearable
              class="mall-select"
              style="width: 120px"
          >
            <el-option label="商品类型" value="byType" />
            <el-option label="商品采购价" value="byPrice" />
            <el-option label="最低库存" value="byStore" />
          </el-select>
        </el-form-item>

        <el-form-item label="查询值">
          <el-input
              v-model="queryProductForm.inputVal"
              placeholder="输入查询值"
              class="mall-input"
              clearable
          />
        </el-form-item>

        <el-form-item label="商品颜色">
          <el-select
              v-model="queryProductForm.pcolor"
              placeholder="选择颜色"
              clearable
              class="mall-select"
              style="width: 120px"
          >
            <el-option label="黑色" :value="0" />
            <el-option label="白色" :value="1" />
            <el-option label="粉色" :value="3" />
            <el-option label="红色" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品品牌">
          <el-select
              v-model="queryProductForm.pbrand"
              placeholder="选择品牌"
              clearable
              class="mall-select"
              @click="queryAllBrank"
              style="width: 120px"
          >
            <el-option
                v-for="brand in brandList"
                :key="brand.brandName"
                :label="brand.brandName"
                :value="brand.brandName"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品分类">
          <el-select
              v-model="queryProductForm.ptype"
              placeholder="选择分类"
              clearable
              class="mall-select"
              @click="queryAllType"
              style="width: 120px"
          >
            <el-option
                v-for="type in typeList"
                :key="type.id"
                :label="type.typeName"
                :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="queryProductByCondition"
              class="mall-btn mall-primary"
          >
            搜索
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mall-table-card" style="margin-top: 16px;">
      <template #header>
        <div class="table-header">
          <span class="table-title">商品列表</span>
          <span class="table-tips">提示：仅可选择一个商品</span>
        </div>
      </template>

      <el-table
          :data="goodsList"
          class="mall-table"
          @selection-change="handleSelectionChange"
          stripe
          v-loading="productLoading"
      >
        <el-table-column label="序号" prop="id" width="70" align="center" />
        <el-table-column type="selection" :selectable="isSelectable" width="60" align="center" />
        <el-table-column label="商品名称" prop="gname" min-width="180" show-overflow-tooltip />
        <el-table-column label="商品类型" prop="typeName" min-width="120" align="center" />
        <el-table-column label="商品采购价" prop="purchasePrice" min-width="120" align="center">
          <template #default="scope">
            <span class="price-cell">¥{{ scope.row.purchasePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品品牌" prop="gbrand" min-width="120" align="center" />
        <el-table-column label="商品型号" prop="gmodel" min-width="150" show-overflow-tooltip />
        <el-table-column label="最低库存" prop="minStock" min-width="100" align="center" />
        <el-table-column label="商品颜色" prop="gcolor" min-width="100" align="center">
          <template #default="scope">
            <el-tag
                :type="getColorType(scope.row.gcolor)"
                class="color-tag"
            >
              <span v-if="scope.row.gcolor == 0">黑色</span>
              <span v-else-if="scope.row.gcolor == 1">白色</span>
              <span v-else-if="scope.row.gcolor == 2">红色</span>
              <span v-else-if="scope.row.gcolor == 3">粉色</span>
              <span v-else>未知</span>
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="chooseProdpageInfo.pageNum"
          v-model:page-size="chooseProdpageInfo.pageSize"
          :page-sizes="[6, 12, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="chooseProdpageInfo.total"
          @size-change="handleChooseSizeChange"
          @current-change="handleChooseCurrentChange"
          class="mall-pagination"
      />
    </div>

    <template #footer>
      <span class="dialog-footer mall-footer">
        <el-button @click="chooseGoodsDialog = false" class="mall-btn mall-default">关闭</el-button>
        <el-button type="primary" @click="closeAndEcho" class="mall-btn mall-primary">保存选择</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
// 原有的script内容完全保持不变
import {ref, onMounted, watch} from "vue";
import api from '@/utils/request.js';
import {ElMessage, ElMessageBox} from "element-plus";
import ViewDialog from './viewDialog.vue';
import AuditTraceDialog from "@/views/check/AuditTraceDialog.vue";
const viewDialogRef = ref();

// 点击"查看"时触发
const handleView = (row) => {
  viewDialogRef.value.openViewDialog(row);
};

/**删除批量删除和单独删除都可以*/
// 存储选中的行数据（完整对象）
const selectedRows = ref([]);
// 存储拼接后的id字符串（如 "11,22,33"）
const selectedIds = ref('');
const getRowIds = (rows) => {
  selectedRows.value = rows;
  selectedIds.value = rows.map(row => row.id).join(',');
};

const delBatch = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请至少选择一个记录");
    return;
  }

  console.log("选中的id：" + selectedIds.value);

  ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '批量删除确认',
      { type: 'warning' }
  ).then(() => {
    api.post(`priceAdjust/del/${selectedIds.value}`).then(result => {
      if (result.code === 200) {
        ElMessage.success('批量删除成功');
        pageInfo.value.pageNum = 1;
        query();
      } else {
        ElMessage.error('删除失败，请重试');
      }
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
/**查看详情*/

/* 新增价格调整相关变量 */
let addAdjustDialog = ref(false);
let chooseGoodsDialog = ref(false);
const selectedGoods = ref(null);
const productLoading = ref(false);

// 表单数据
const form = ref({
  goodsId: '',
  goodsName: '',
  goodsStock: '',
  originalMarketPrice: '',
  originalMallPrice: '',
  adjustWay: 'absolute',
  percent: '',
  adjustMarketPrice: '',
  adjustShoppingPrice: '',
  beginTime: '',
  endTime: '',
  reason: '',
  remark: ''
});
//*自动计算*//

/* 调价逻辑（核心实现） */
// 监听调整方式变化
const handleAdjustWayChange = () => {
  form.value.percent = '';
  calculateAdjustedPrices();
};

// 处理调整值输入
const handlePercentInput = (value) => {
  let processedValue = value;

  if (form.value.adjustWay === 'percentage') {
    processedValue = processedValue.replace(/[^0-9%]/g, '');
    if (processedValue.indexOf('%') > -1) {
      processedValue = processedValue.replace(/%/g, '').concat('%');
    }
    if (processedValue.startsWith('-')) {
      processedValue = processedValue.replace(/-/g, '');
    }
  } else {
    processedValue = processedValue.replace(/[^0-9.]/g, '');
    if (processedValue.startsWith('-')) {
      processedValue = processedValue.replace(/-/g, '');
    }
    if ((processedValue.match(/\./g) || []).length > 1) {
      processedValue = processedValue.slice(0, processedValue.lastIndexOf('.'));
    }
  }

  form.value.percent = processedValue;
  calculateAdjustedPrices();
};

// 计算调整后价格
const calculateAdjustedPrices = () => {
  if (!form.value.originalMarketPrice || !form.value.originalMallPrice) {
    form.value.adjustMarketPrice = '';
    form.value.adjustShoppingPrice = '';
    return;
  }

  const originalMarket = Number(form.value.originalMarketPrice) || 0;
  const originalMall = Number(form.value.originalMallPrice) || 0;
  let adjustValue = 0;
  const percentStr = form.value.percent ? String(form.value.percent).trim() : '';

  if (form.value.adjustWay === 'percentage') {
    if (!percentStr) {
      form.value.adjustMarketPrice = '';
      form.value.adjustShoppingPrice = '';
      return;
    }

    const percentNum = Number(percentStr.replace('%', ''));
    adjustValue = percentNum / 100;

    if (isNaN(adjustValue) || adjustValue < 0) {
      form.value.adjustMarketPrice = '';
      form.value.adjustShoppingPrice = '';
      return;
    }

    form.value.adjustMarketPrice = (originalMarket * adjustValue).toFixed(2);
    form.value.adjustShoppingPrice = (originalMall * adjustValue).toFixed(2);
  } else {
    if (!percentStr) {
      form.value.adjustMarketPrice = '';
      form.value.adjustShoppingPrice = '';
      return;
    }

    adjustValue = Number(percentStr);

    if (isNaN(adjustValue) || adjustValue < 0) {
      form.value.adjustMarketPrice = '';
      form.value.adjustShoppingPrice = '';
      return;
    }

    form.value.adjustMarketPrice = adjustValue.toFixed(2);
    form.value.adjustShoppingPrice = adjustValue.toFixed(2);
  }
};

watch(() => form.value.originalMarketPrice, () => {
  calculateAdjustedPrices();
});

/* 时间选择器限制 */
const disabledEffectiveDate = (time) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

const disabledInvalidDate = (time) => {
  const effectiveDate = new Date(form.value.beginTime);
  return time.getTime() <= effectiveDate.getTime();
};

const handleEffectiveTimeChange = () => {
  if (!form.value.beginTime) {
    form.value.endTime = '';
    return;
  }
  if (form.value.endTime) {
    const effective = new Date(form.value.beginTime);
    const invalid = new Date(form.value.endTime);
    if (invalid <= effective) {
      form.value.endTime = '';
    }
  }
};

const checkEffectiveTimeFirst = () => {
  if (!form.value.beginTime) {
    ElMessage.warning('请先选择生效时间');
  }
};

/* 选择商品相关逻辑 */
const openchooseGoodsDialog = () => {
  selectedGoods.value = null;
  showProdList();
};

const handleSelectionChange = (selectedItems) => {
  if (selectedItems.length > 1) {
    selectedGoods.value = selectedItems[selectedItems.length - 1];
    const table = document.querySelector('.el-table').__vue__;
    table.clearSelection();
    table.toggleRowSelection(selectedGoods.value, true);
  } else if (selectedItems.length === 1) {
    selectedGoods.value = selectedItems[0];
  } else {
    selectedGoods.value = null;
  }
};

const isSelectable = (row) => {
  if (selectedGoods.value && selectedGoods.value.id !== row.id) {
    return false;
  }
  return true;
};

const closeAndEcho = () => {
  if (!selectedGoods.value) {
    ElMessage.warning('请先勾选一个商品');
    return;
  }

  const goods = selectedGoods.value;
  form.value = {
    ...form.value,
    goodsId: goods.id || '',
    goodsName: goods.gname || '',
    goodsStock: goods.stock || '',
    originalMarketPrice: goods.marketPrice || '',
    originalMallPrice: goods.shopPrice || ''
  };

  chooseGoodsDialog.value = false;
  selectedGoods.value = null;
  ElMessage.success('商品选择成功');
};

/* 商品列表查询 */
const queryProductForm = ref({
  pname: "",
  pmodel: "",
  queryconditon: "",
  inputVal: "",
  pcolor: "",
  pbrand: "",
  ptype: ""
});

const chooseProdpageInfo = ref({
  pageNum: 1,
  pageSize: 6,
  total: 0
});

let goodsList = ref([]);
let typeList = ref([]);
let brandList = ref([]);

const showProdList = () => {
  productLoading.value = true;
  chooseGoodsDialog.value = true;

  const searchParams = {
    ...queryProductForm.value,
    ...chooseProdpageInfo.value
  };

  api.get("GcGoods/listAll", searchParams).then(result => {
    goodsList.value = result.data.list;
    chooseProdpageInfo.value.total = result.data.total;
  }).finally(() => {
    productLoading.value = false;
  });
};

const queryAllBrank = () => {
  api.get("GgBrand/listAllBrand1").then(result => {
    brandList.value = result.data;
  });
};

const queryAllType = () => {
  api.get("GgType/listAllType1").then(result => {
    typeList.value = result.data.filter(type => type.id != 10);
  });
};

const queryProductByCondition = () => {
  chooseProdpageInfo.value.pageNum = 1;
  showProdList();
};

const handleChooseSizeChange = (pageSize) => {
  chooseProdpageInfo.value.pageSize = pageSize;
  chooseProdpageInfo.value.pageNum = 1;
  showProdList();
};

const handleChooseCurrentChange = (pageNum) => {
  chooseProdpageInfo.value.pageNum = pageNum;
  showProdList();
};

const closeQueryPro = () => {
  queryProductForm.value = {
    pname: "",
    pmodel: "",
    queryconditon: "",
    inputVal: "",
    pcolor: "",
    pbrand: "",
    ptype: ""
  };
  chooseProdpageInfo.value.pageNum = 1;
  chooseProdpageInfo.value.pageSize = 6;
  selectedGoods.value = null;
  chooseGoodsDialog.value = false;
};

/* 主表格查询逻辑 */
const queryForm = ref({
  gname: "",
  processStatus: "",
  beginTime: "",
  endTime: ""
});

const pageInfo = ref({
  pageNum: 1,
  pageSize: 3,
  total: 0
});

const priceTableData = ref([]);

const query = () => {
  const queryParam = { ...queryForm.value, ...pageInfo.value };
  api.get("priceAdjust/list", queryParam).then(result => {
    if (result.code === 200) {
      pageInfo.value.total = result.data.total;
      priceTableData.value = result.data.list;
    }
  });
};

const queryWithCondition = () => {
  pageInfo.value.pageNum = 1;
  query();
};

const clearQueryForm = () => {
  queryForm.value = {
    gname: "",
    processStatus: "",
    beginTime: "",
    endTime: ""
  };
  pageInfo.value.pageNum = 1;
  query();
};

const pageSizeChange = (pageSize) => {
  pageInfo.value.pageSize = pageSize;
  pageInfo.value.pageNum = 1;
  query();
};

const pageNumChange = (pageNum) => {
  pageInfo.value.pageNum = pageNum;
  query();
};

/* 工具方法 */
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}年${month}月${day}日`;
};

const getColorType = (color) => {
  const types = ['', 'success', 'danger', 'warning'];
  return types[color] || 'info';
};

const resetForm=()=>{
  form.value.goodsId = '';
  form.value.goodsName = '';
  form.value.goodsStock = '';
  form.value.originalMarketPrice = '';
  form.value.originalMallPrice = '';
  form.value.adjustWay="absolute"
  form.value.percent = '';
  form.value.adjustMarketPrice = '';
  form.value.adjustShoppingPrice = '';
  form.value.beginTime = '';
  form.value.endTime = '';
  form.value.reason = '';
  form.value.remark = '';
}

/* 对话框及表单操作 */
const handleClose = () => {
  addAdjustDialog.value = false;
  resetForm()
};

//保存按钮
/* 表单校验规则 */
const formRules = ref({
  goodsId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  percent: [
    { required: true, message: '请输入调价幅度', trigger: 'blur' }
  ],
  adjustMarketPrice: [
    { required: true, message: '调整后价格不能为空', trigger: 'blur' }
  ],
  adjustShoppingPrice: [
    { required: true, message: '调整后价格不能为空', trigger: 'blur' }
  ],
  beginTime: [
    { required: true, message: '请选择生效时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择失效时间', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入调价原因', trigger: 'blur' }
  ]
});

// 获取表单引用
const formRef = ref();

/* 保存表单前的校验 */
const saveForm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    console.log("保存表单数据：", form.value);
    api.post("priceAdjust/save/update", form.value).then(result => {
      if (result.code == 200) {
        ElMessage.success("保存/修改成功");
        addAdjustDialog.value = false;
        resetForm();
        pageInfo.value.pageNum = 1;
        query();
      } else {
        ElMessage.error("保存失败，联系管理");
      }
    });

  } catch (error) {
    ElMessage.warning('请填写完整表单信息');
    console.log('表单校验失败:', error);
  }
  const { id, ...submitData } = form.value;
  form.value=submitData
};

/*修改功能*/
const handleEdit = (row) => {
  console.log("修改", row);
  form.value = {
    goodsId: row.goodsId || '',
    goodsName: row.gname || '',
    goodsStock: row.stock || '',
    originalMarketPrice: row.oldMarketPrice || '',
    originalMallPrice: row.oldShopPrice || '',
    adjustWay: row.adjustWay || 'absolute',
    percent: row.percent || '',
    adjustMarketPrice: row.adjustMarketPrice || '',
    adjustShoppingPrice: row.adjustShoppingPrice || '',
    beginTime: row.beginTime ? formatRowDate(row.beginTime) : '',
    endTime: row.endTime ? formatRowDate(row.endTime) : '',
    reason: row.reason || '',
    remark: row.remark || '',
    id:row.id,
  };
  addAdjustDialog.value = true
  console.log(form.value)
}

const formatRowDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

//删除或者批量删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定要删除这条价格调整记录吗？',
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        api.post(`priceAdjust/del/${row.id}`).then(result => {
          if (result.code === 200) {
            ElMessage.success('删除成功');
            pageInfo.value.pageNum=1
            query();
          } else {
            ElMessage.error('删除失败，请重试');
          }
        }).catch(() => {
          ElMessage.error('网络错误，删除失败');
        });
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

// 禁用结束日期的逻辑：结束日期不能早于开始日期
const disabledEndDate = (time) => {
  if (queryForm.value.beginTime) {
    const beginDate = new Date(queryForm.value.beginTime);
    return time.getTime() < beginDate.getTime();
  }
  return false;
};

// 开始日期变化时，清空结束日期（可选，避免结束日期仍停留在旧的开始日期之前）
const handleBeginTimeChange = () => {
  if (queryForm.value.endTime && queryForm.value.beginTime) {
    const beginDate = new Date(queryForm.value.beginTime);
    const endDate = new Date(queryForm.value.endTime);
    if (endDate < beginDate) {
      queryForm.value.endTime = '';
    }
  }
};

const auditTraceDialogRef = ref();

const handleAuditTrace = (row) => {
  auditTraceDialogRef.value.openAuditTraceDialog(row);
};

/* 初始化 */
onMounted(() => {
  query();
});
</script>

<style scoped>
/* 商场主题样式 */
.mall-query-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.mall-query-form {
  padding: 20px;
}

.mall-query-form :deep(.el-form-item__label) {
  color: white;
  font-weight: 600;
}

.mall-input {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.mall-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.mall-input.mall-disabled {
  background-color: #f5f7fa;
  color: #909399;
}

.mall-select {
  border-radius: 8px;
}

.mall-date {
  border-radius: 8px;
}

.mall-date.full-date {
  width: 100%;
}

.mall-btn {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
}

.mall-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.mall-primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.mall-success {
  background: linear-gradient(135deg, #42b983, #66bb6a);
  color: white;
}

.mall-danger {
  background: linear-gradient(135deg, #ff6b6b, #ff5252);
  color: white;
}

.mall-default {
  background: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.mall-info {
  background: linear-gradient(135deg, #4fc3f7, #29b6f6);
  color: white;
}

.query-buttons {
  margin-left: auto;
}

.mall-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.mall-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin: 0;
}

.mall-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.dialog-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  margin: -20px -20px 20px -20px;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.mall-dialog-form {
  padding: 20px;
}

.mall-dialog-form :deep(.el-form-item__label) {
  color: #333;
  font-weight: 600;
}

.form-item-content {
  display: flex;
  gap: 10px;
  align-items: center;
}

.mall-radio-group {
  display: flex;
  gap: 20px;
}

.mall-radio :deep(.el-radio__label) {
  color: #333;
}

.adjust-group {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.adjust-input {
  width: 150px;
}

.price-group {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.price-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-label {
  color: #666;
  font-size: 14px;
  min-width: 50px;
}

.price-input {
  width: 180px;
}

.mall-textarea {
  border-radius: 8px;
  resize: vertical;
}

.mall-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e8e8e8;
}

.mall-table-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e8e8e8;
}

.table-title {
  color: #333;
  font-weight: 600;
  font-size: 16px;
}

.table-tips {
  color: #666;
  font-size: 12px;
}

.mall-table {
  border-radius: 8px;
  overflow: hidden;
}

.mall-table :deep(th) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%) !important;
  color: #333;
  font-weight: 600;
  border: none;
}

.mall-table :deep(td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 0;
}

.price-cell {
  font-weight: 600;
  color: #333;
}

.price-cell.highlight {
  color: #ff6b6b;
  font-weight: 700;
}

.date-cell {
  color: #666;
  font-size: 13px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-unreviewed {
  background: #fff3e0;
  color: #ff9800;
  border: 1px solid #ffb74d;
}

.status-passed {
  background: #e8f5e8;
  color: #4caf50;
  border: 1px solid #81c784;
}

.status-rejected {
  background: #ffebee;
  color: #f44336;
  border: 1px solid #e57373;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.pagination-container {
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.mall-pagination {
  justify-content: center;
}

.mall-search-card {
  border-radius: 8px;
  margin-bottom: 16px;
}

.mall-search-form {
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.mall-search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.color-tag {
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .mall-query-form {
    flex-direction: column;
    align-items: stretch;
  }

  .query-buttons {
    margin-left: 0;
    margin-top: 16px;
  }

  .adjust-group,
  .price-group {
    flex-direction: column;
    align-items: flex-start;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style>